package cn.edu.zafu.bigdata.fui;

import java.io.*;

class fileUtils{
    public static void writeToFile(String fileName, String content) throws IOException{
        writeToFile(fileName, content, false);
    }
    public static void writeToFile(String fileName, String content, boolean isAppend) throws IOException{
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("src/main/java/cn/edu/zafu/bigdata/fui/files/"+ fileName + ".txt", isAppend)) ){
            writer.write(content);
        } catch (IOException e){
            System.out.println(e.getMessage());
        }
    }
    public static void readFromFile(String fileName) throws IOException{
        try (BufferedReader reader = new BufferedReader(new FileReader("src/main/java/cn/edu/zafu/bigdata/fui/files/"+ fileName + ".txt")) ){
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
            String line;
            while((line = reader.readLine()) != null){
                out.write(line);
                out.newLine();
            }
            out.close();
        } catch (IOException e){
            System.out.println(e.getMessage());
        }
    }

}

public class TestFileRnW {
    public static void main(String[] args) throws IOException {
        String fileName;
        String line;
        StringBuilder content = new StringBuilder();

        try (BufferedReader in = new BufferedReader(new InputStreamReader(System.in)) ) {
            System.out.println("请输入文件名称：");
            fileName = in.readLine();

            System.out.println("请输入文件内容,末行输入##结束：");
            while((line = in.readLine()) != null && !"##".equals(line)){
                content.append(line);
                content.append('\n');
            }

            fileUtils.writeToFile(fileName, content.toString(),true);
            System.out.println("文件写入完成");

            System.out.println("打开文件" + fileName+ " :" + "\n");
            fileUtils.readFromFile(fileName);
        } catch (IOException e){
            System.out.println(e.getMessage());
        }
    }
}
/*2. (简答题)
题目2：写入并读取文本文件
描述：
编写一个程序，将用户输入的文本保存到一个文件中（files目录下的学号文本文件，如files/2022010101.txt），然后读取并显示文件的内容。
具体要求：
写入文件：创建一个方法writeToFile(String fileName, String content)，将用户输入的文本写入到指定的文件中。
读取文件：创建一个方法readFromFile(String fileName)，读取文件内容并将其打印到控制台。
测试：在main方法中，提示用户输入文本，将其写入文件，然后读取并显示文件内容。*/